import { defineStore } from "pinia";
import { Message } from "@arco-design/web-vue";
import * as userBaseApi from "@/api/user-base";

export const useUserBaseStore = defineStore("userBase", () => {
  async function getUsers(param?: any) {
    const response = await userBaseApi.getUsers(param);
    if (response.code === 20000) {
      return response.data.users;
    }
    return [];
  }

  async function getUser(param?: any) {
    const response = await userBaseApi.getUser(param);
    if (response.code === 20000) {
      return response.data.user;
    }
    return {};
  }

  async function saveUser(param?: any) {
    const apiCall = param.id ? userBaseApi.updateUser : userBaseApi.createUser;
    const response = await apiCall({ ...param });
    if (response.code === 20000) {
      Message.success(param.id ? "更新成功" : "新增成功");
    }
  }

  async function deleteUser(param?: any) {
    const response = await userBaseApi.deleteUser(param);
    if (response.code === 20000) {
      Message.success("移除成功");
    }
  }

  async function getRoles(param?: any) {
    const response = await userBaseApi.getRoles(param);
    if (response.code === 20000) {
      return response.data.roles;
    }
    return [];
  }

  async function saveRole(param?: any) {
    const apiCall = param.id ? userBaseApi.updateRole : userBaseApi.createRole;
    const response = await apiCall({ ...param });
    if (response.code === 20000) {
      Message.success(param.id ? "更新成功" : "新增成功");
    }
  }

  async function deleteRole(param?: any) {
    const response = await userBaseApi.deleteRole(param);
    if (response.code === 20000) {
      Message.success("移除成功");
    }
  }

  async function getRole(param?: any) {
    const response = await userBaseApi.getRole(param);
    if (response.code === 20000) {
      return response.data.role;
    }
    return {};
  }

  return {
    getUsers,
    getUser,
    saveUser,
    deleteUser,
    getRoles,
    saveRole,
    deleteRole,
    getRole,
  };
});
